﻿using AutoMapper;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.ProcessEgine.API.Applocations.Commands.FormTypeInfoCommand;
using B.S.ProcessEgine.Domain.Entities;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormTypeInfoHandler
{
    public class AddFormTypeInfoHandler:IRequestHandler<AddFormTypeInfoCommand,ApiResult>
    {
        IFormTypeRepository formtypeinforepository;
        ILogger<AddFormTypeInfoHandler> logger;
        IMapper mapper;

        public AddFormTypeInfoHandler(IFormTypeRepository formtypeinforepository, ILogger<AddFormTypeInfoHandler> logger,IMapper mapper)
        {
            this.formtypeinforepository = formtypeinforepository;
            this.logger = logger;
            this.mapper = mapper;
        }
        /// <summary>
        /// 表单添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult> Handle(AddFormTypeInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //获取最后一个添加的编号
                var lastTypeNo = await formtypeinforepository.GetAll().OrderByDescending(x => x.TypeId).Select(x => x.TypeNo).FirstOrDefaultAsync();
                //如果数据库没有数据，则设置编号为T000001
                if (string.IsNullOrWhiteSpace(lastTypeNo))
                {
                    request.data.TypeNo = "T000001";
                }
                //如果有数据，则在最后一个编号的基础上加1
                else
                {

                    //通过Substring(1)截取到他的编号
                    var lastNumber = int.Parse(lastTypeNo.Substring(1));
                    request.data.TypeNo = "T" + (lastNumber + 1).ToString("D6");

                }
                var res = await formtypeinforepository.AddAsync(request.data);

                return res>0?ApiResult.Success(StateCodeEnum.Ok):ApiResult.Fail("添加失败",StateCodeEnum.Fail);
            }
            catch (Exception ex)
            {
                logger.LogError("表单添加出错" + ex.Message);
                throw;
            }
        }
    }
}
